#include <signal.h>

#include <iostream>
using std::cout;
using std::endl;
using std::string;

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpUtil.h>
#include <workflow/HttpMessage.h>


//通过构造函数初始化计数器的值 
static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig %d is coming\n", num);
    //将计数器的值减1
    waitGroup.done();
}

void httpCallback(WFHttpTask * httptask)
{
    printf("httpCallback is runnging.\n");
    //0. 对任务本身的状态进行检测
    int state = httptask->get_state();
    int error = httptask->get_error();
    switch(state) {
    case WFT_STATE_SYS_ERROR:
        printf("sys error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        printf("dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        break;
    }
    if(state != WFT_STATE_SUCCESS) {
        printf("task error!\n");
        return;
    }
    
    /* printf("task is success!\n"); */
    //1. 打印请求报文的信息
    auto req = httptask->get_req();
    //1.1 打印起始行
    printf("%s %s %s\n", req->get_method(),
           req->get_request_uri(),
           req->get_http_version());
    //1.2 打印首部字段
    protocol::HttpHeaderCursor cursor(req);
    string key("HOST"), val;
    if(cursor.find(key, val)) {
        cout << key << ": " << val << endl;
    }
    /* while(cursor.next(key, val)) { */
    /*     cout << key << ": " << val << endl; */
    /* } */
    /* cout << endl; */
    
    //2. 打印响应报文的信息
    //2.1 起始行
    auto resp = httptask->get_resp();
    printf("%s %s %s\n", resp->get_http_version(),
           resp->get_status_code(),
           resp->get_reason_phrase());
    //2.2 打印首部字段
    /* protocol::HttpHeaderCursor cursor2(resp); */
    /* while(cursor2.next(key, val)) { */
    /*     cout << key << ": " << val << endl; */
    /* } */
    /* cout << endl; */
    //2.3 打印消息体
    const void * pbody = nullptr;
    size_t sz = 0;
    resp->get_parsed_body(&pbody, &sz);
    printf("body's size: %ld\n\n\n", sz);
    //printf("%s\n", (const char *)pbody);
}


void test0()
{
    signal(SIGINT, sighandler);
    std::vector<string> webs{
        "http://www.baidu.com",
        "http://www.mi.com",
        "http://www.qq.com",
    };

    auto parallelWork = Workflow::create_parallel_work(nullptr);
    for(size_t i = 0; i < webs.size(); ++i) {
        //1. 创建HTTP任务
        WFHttpTask * httpTask = WFTaskFactory::create_http_task(webs[i], 0, 1, httpCallback);
        //2. 设置任务的属性
        httpTask->get_req()->set_header_pair("User-Agent","Workflow HttpClient");
        //3. 创建序列
        auto series = Workflow::create_series_work(httpTask, nullptr);
        parallelWork->add_series(series);
    }
    parallelWork->start();

    waitGroup.wait();
}


int main()
{
    test0();
    printf("exit main\n");
    return 0;
}

